package org.dromara.javalin;

import cn.hutool.core.annotation.AnnotationUtil;
import cn.hutool.core.util.ReflectUtil;
import io.javalin.apibuilder.ApiBuilder;
import io.javalin.apibuilder.EndpointGroup;
import io.javalin.http.Handler;
import org.dromara.javalin.annotation.*;
import org.dromara.javalin.handler.SaTokenCheckHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;

public class SaTokenEndpointGroup implements EndpointGroup {

    private static final Logger log = LoggerFactory.getLogger(SaTokenEndpointGroup.class);
    private final Object webHandler;
    private final Method[] methods;
    private final WebHandler webHandlerAnnotation;

    public SaTokenEndpointGroup(WebHandler webHandlerAnno, Object webHandler, Method[] methods) {
        this.webHandler = webHandler;
        this.webHandlerAnnotation = webHandlerAnno;
        this.methods = methods;
    }

    @Override
    public void addEndpoints() {
        String path = webHandlerAnnotation.value();
        ApiBuilder.path(path, () -> {
                    for (Method method : methods) {
                        Handler saTokenHandler = new SaTokenCheckHandler(method, context -> ReflectUtil.invoke(webHandler, method, context));
                        Get get = AnnotationUtil.getAnnotation(method, Get.class);
                        if (get != null) {
                            ApiBuilder.get(get.value(), saTokenHandler);
                            log.debug("register web handler Get {} for {}", path, get.value());
                            continue;
                        }
                        Put put = AnnotationUtil.getAnnotation(method, Put.class);
                        if (put != null) {
                            ApiBuilder.put(put.value(), saTokenHandler);
                            log.debug("register web handler Put {} for {}", path, put.value());
                            continue;
                        }
                        Post post = AnnotationUtil.getAnnotation(method, Post.class);
                        if (post != null) {
                            ApiBuilder.post(post.value(), saTokenHandler);
                            log.debug("register web handler Post {} for {}", path, post.value());
                            continue;
                        }
                        Delete delete = AnnotationUtil.getAnnotation(method, Delete.class);
                        if (delete != null) {
                            log.debug("register web handler Delete {} for {}", path, delete.value());
                            ApiBuilder.delete(delete.value(), saTokenHandler);
                        }
                    }
                }
        );
    }
}
